<?php
/**
 * Project: AIGC
 * Author: moufer <moufer@163.com>
 * Date: 2024/7/18 16:29
 */

namespace module\user\middleware;

use Closure;
use module\user\library\Auth;
use mof\ApiResponse;
use mof\exception\AuthTokenException;
use mof\Request;
use think\Response;

class AuthTokenMiddleware
{
    /**
     * 处理请求
     *
     * @param Request $request
     * @param Closure $next
     * @return Response
     */
    public function handle(Request $request, Closure $next): Response
    {
        //验证header中的token，token是jwt生成的，验证通过则返回用户信息
        $token = $request->header('Authorization');
        if ($token && str_starts_with($token, 'Bearer ')) {
            try {
                $auth = app(Auth::class);
                $auth->verify(substr($token, 7));
                //获取用户信息
                if ($auth->getUser()->status !== 1) {
                    return ApiResponse::noPermission('当前账号已被禁用');
                }
                $request->user = $auth->getUser()->hidden(['password']);
            } catch (AuthTokenException) {
                //return ApiResponse::needLogin($e->getMessage());
            }
        }
        return $next($request);
    }
}